package com.hedl.practice.diyJava.jdbc.test;

import com.hedl.practice.diyJava.jdbc.pojo.Student;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class Client {
    static final String Url = "jdbc:mysql://localhost:3306/jdbcStudy?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8";
    static final String Username = "root";
    static final String Password = "shupian226";

    static List<Student> queryStudents()throws SQLException {
        List<Student>students = new ArrayList<>();
        try(Connection conn = DriverManager.getConnection(Url,Username,Password)){
            try(PreparedStatement ps = conn.prepareStatement("SELECT * FROM student WHERE grade = ? AND score >= ?")){
                ps.setInt(1,3);
                ps.setInt(2,90);
                try(ResultSet rs = ps.executeQuery()){
                    while(rs.next()){
                        students.add(extractRow(rs));
                    }
                }
            }
        }
        return students;
    }

    static Student extractRow(ResultSet rs)throws SQLException{
        var std = new Student();
        std.setId(rs.getLong("id"));
        std.setName(rs.getString("name"));
        std.setGender(rs.getBoolean("gender"));
        std.setGrade(rs.getInt("grade"));
        std.setScore(rs.getInt("score"));
        return std;
    }

    public static void main(String[] args) throws Exception{
        List<Student> students = queryStudents();
        students.forEach(System.out::println);
    }


}
